import CryptoJS from 'crypto-js'
import hex_md5 from './md5'

function urlencode (str) {
  str = (str + '').toString()

  return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28')
      .replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+')
}
/**
 *
 * 第一个参数word是待加密或者解密的字符串；
 * 第二个参数keyStr是aes加密需要用到的16位字符串的key；
 *
 * 如果想对一个js对象加密，需要先把该对象转成json字符串。
 */
export default {
  // 加密
  encrypt (word, keyStr) {
    keyStr = keyStr || 'qwer12344321rewq'
    const key = CryptoJS.enc.Utf8.parse(keyStr)
    const srcs = CryptoJS.enc.Utf8.parse(word)
    const encrypted = CryptoJS.AES.encrypt(srcs, key, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7
    })
    return encrypted.toString()
  },
  // 解密
  decrypt (word, keyStr) {
    keyStr = keyStr || 'qwer12344321rewq'
    var key = CryptoJS.enc.Utf8.parse(keyStr)
    var decrypt = CryptoJS.AES.decrypt(word, key, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7
    })
    return CryptoJS.enc.Utf8.stringify(decrypt).toString()
  },
  sign (params, appKey, appSecret) {
    const obj = {}
    let str = ''
    for (const k in params) {
      if (['sign', 'appKey'].includes(k) || k instanceof Array || k instanceof Object || params[k] === undefined) {
        continue
      }
      if (params[k] instanceof Array) {
        obj[k] = JSON.stringify(params[k])
      } else {
        obj[k] = params[k]
      }
    }
    Object.keys(obj).sort().forEach(k => {
      str += obj[k]
    })
    console.log(`${appKey}${str}${appSecret}`)
    str = urlencode(`${appKey}${str}${appSecret}`).toUpperCase()
    return hex_md5(str)
  }
}
